package com.ujs.edu.medicine.controller;

import com.alibaba.fastjson.JSONArray;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.ujs.edu.medicine.JWT.CheckToken;
import com.ujs.edu.medicine.dao.*;
import com.ujs.edu.medicine.dataobject.*;
import com.ujs.edu.medicine.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ujs.edu.medicine.JWT.JwtUtil;
import com.ujs.edu.medicine.JWT.LoginToken;
import com.ujs.edu.medicine.util.QiNiuFileUpUtil;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.fastjson.JSONObject;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;


@RestController
@RequestMapping("/api/user")
public class UserController {
    @Autowired
    private YunjiayiUserMapper yunjiayiUserMapper;
    @Autowired
    private YunjiayiIdcardMapper YunjiayiIdcardMapper;
    @Autowired
    private YunjiayiVerifyMapper yunjiayiVerifyMapper;
    @Autowired
    private YunjiayiIdcardMapper yunjiayiIdcardMapper;
    @Autowired
    private YunjiayiPostMapper yunjiayiPostMapper;
    @Autowired
    private CollectUSMapper collectUSMapper;
    @Autowired
    private YunjiayiShopMapper yunjiayiShopMapper;
    @Autowired
    private YunjiayiLikeMapper yunjiayiLikeMapper;
    @Autowired
    private HttpServletRequest request;

    private String gettoken() {
        return request.getHeader("Authorization");
    }

    //post,新增,用户注册
    @RequestMapping(path = "/enroll", method = RequestMethod.POST)
    public Result enroll(@RequestBody Map<String, String> map) {
        Result result = new Result();
        YunjiayiUser user = new YunjiayiUser();

        YunjiayiUser users = yunjiayiUserMapper.selectByName(map.get("username"));
        user.setPassword(map.get("password"));
        user.setUsername(map.get("username"));
        user.setRealname(map.get("realname"));
        user.setAvatar("http://cloud-medicine.youchen-blog.cn/default.jpg");
        user.setIdentityId(Integer.parseInt(map.get("identify_id")));
        user.setStatusID(3);
        user.setContent(map.get("identify_id"));

        if (users == null) {
            int addUser = yunjiayiUserMapper.insert(user);
            user = yunjiayiUserMapper.selectByName(map.get("username"));
            if (Integer.parseInt(map.get("identify_id")) == 5) {
                YunjiayiShop shop = new YunjiayiShop();
                shop.setShopid(user.getUser_Id());
                shop.setShopimage(user.getAvatar());
                shop.setShopname(user.getRealname());

                try {
                    int insertshop = yunjiayiShopMapper.insert(shop);
                } catch (Exception e) {
                    result.setCode(1);
                    result.setMessage("注册药店失败");
                }


            }
            String token = JwtUtil.createJWT(6000000, user);
            if (addUser == 1) {
                result.setCode(0);
                result.setData(token);
                result.setMessage("注册成功");
            } else {
                result.setCode(1);
                result.setMessage("注册失败，未知原因");
            }
        } else {
            result.setCode(1);
            result.setMessage("注册失败，用户名已存在");
        }
        return result;
    }

    //get,更具id查询用户，获取身份
    @GetMapping(path = "/identify")
    public Result Identify() {
        Result result = new Result();
        List<YunjiayiIdcard> card = YunjiayiIdcardMapper.selectAll();
        if (card != null) {
            result.setCode(0);
            result.setMessage("获取成功");
            result.setData(card);
        } else {
            result.setCode(1);
            result.setMessage("获取失败");
        }
        return result;
    }

    //登录
    @PutMapping(path = "/login")
    @LoginToken
    public Result login(@RequestBody JSONObject object) {
        Result result = new Result();
        YunjiayiUser user1 = yunjiayiUserMapper.selectByName(object.getString("username"));

        if( object.getBoolean("isAdmin")== true){
            if (user1.getIdentityId()!=6||user1.getStatusID()!=6){
                result.setCode(1);
                result.setMessage("你不是管理员");
                return result;
            }
        }
        if (user1 == null) {
            result.setCode(1);
            result.setMessage("登录失败，用户不存在");
        } else {
            if (user1.getPassword().equals(object.get("password"))) {
                String token = JwtUtil.createJWT(6000000, user1);
                result.setCode(0);
                result.setData(token);
                result.setMessage("登录成功");
            } else {
                result.setCode(1);
                result.setMessage("登录失败，密码错误");
            }
        }
        return result;
    }

    /*获取用户基本信息*/
    @GetMapping(path = "/basic")
    public Result getUserBasic(@RequestParam(value = "userID", required = false) Integer userID) {

        Result result = new Result();
        JSONObject object=new JSONObject();
        JSONObject object1=new JSONObject();

        String token = gettoken();
        int userId = 0;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登录");
            return result;
        }
        YunjiayiUser user=null;
        if (userID!=null){
           user=yunjiayiUserMapper.selectByPrimaryKey(userID);
        }else {
           user=yunjiayiUserMapper.selectByPrimaryKey(userId);
        }


        if (user.getStatusID() < 3) {
            switch (user.getStatusID()){
                case 0:{
                    object1.put("id",0);
                    object1.put("value","未验证");
                }
                break;
                case 1:{
                    object1.put("id",1);
                    object1.put("value","验证失败");
                }
                break;
                case 2:{
                    object1.put("id",2);
                    object1.put("value","验证中");
                }
                break;
                default:
                    break;
            }
        }else {
            object1.put("id",user.getIdentityId());
            switch (user.getIdentityId()){
                case 3:
                    object1.put("value","患者");
                    break;
                case 4:
                    object1.put("value","医生");
                    break;
                case 5:
                    object1.put("value","药店");
                    break;
                case 6:
                    object1.put("value","管理员");
                    break;
                default:
                    break;
            }
        }


        try {
            Integer postNum=yunjiayiPostMapper.selectPostNum(userId);
            Integer collectNum=collectUSMapper.selectCollectShopNum(userId);
            Integer likeNum=yunjiayiLikeMapper.countLikeNumByUId(userId);

            user.setPostNum(Integer.toString(postNum));
            user.setCollectNum(Integer.toString(collectNum));
            user.setLikeNum(Integer.toString(likeNum));
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("统计数量出错");
            return result;
        }


        if (user!=null){
            try {
                object.put("avatar",user.getAvatar());
                object.put("realname",user.getRealname());
                object.put("identify",object1);
                if (user.getIdentityId()==4){
                    object.put("statusID",user.getStatusID());
                }else {
                    object.put("statusID",0);
                }

                object.put("money",Float.toString(user.getMoney()));
                object.put("postNum",user.getPostNum().toString());
                object.put("likeNum",user.getLikeNum());
                object.put("collectNum",user.getCollectNum());
            }catch (Exception e){
                result.setCode(1);
                result.setMessage("赋值失败");
                return result;
            }

            result.setCode(0);
            result.setMessage("成功");
            result.setData(object);
        }else {
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return result;
    }

    /*上传文件*/
    @PostMapping(path = "/upFile")
    public Result upFile(@RequestParam(value = "file") MultipartFile file) {
        Result result = new Result();
        String key = file.getOriginalFilename();
        byte[] uploadBytes = new byte[50000000];
        try {
            uploadBytes = file.getBytes();
        } catch (IOException e) {
            System.out.println("异常");
        }
        if (file != null) {
            String Url = QiNiuFileUpUtil.upload(uploadBytes, key);
            result.setCode(Url.equals("") ? 1 : 0);
            result.setData("http://" + Url);
            result.setMessage(Url.equals("") ? "上传失败" : "上传成功");
        } else {
            result.setCode(0);
            result.setMessage("上传失败，文件为空");
        }
        return result;
    }


    /*修改用户详情信息*/
    @PutMapping(path = "/userInfo")
    public Result putUserInfo(@RequestBody Map<String, String> map) {
        Result result = new Result();
        String token = gettoken();
        int userId;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (JWTDecodeException j) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }
        YunjiayiUser user1 = yunjiayiUserMapper.selectByPrimaryKey(userId);
        user1.setPhonenumber(map.get("phonenumber"));
        user1.setRealname(map.get("name"));
        user1.setSex(Integer.parseInt(map.get("sex")));
        user1.setAge(map.get("age"));
        int tip = yunjiayiUserMapper.updateByPrimaryKey(user1);
        result.setCode(tip == 0 ? 1 : 0);
        result.setMessage(tip != 0 ? "修改成功" : "修改失败");
        return result;
    }

    /*获取用户用户详细信息*/
    @GetMapping(path = "/userInfo")
    public Result getUserInfo() {
        JSONObject jsonObject = new JSONObject();
        Result result = new Result();

        String token = gettoken();
        int userId = 0;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }
        YunjiayiUser user1 = new YunjiayiUser();
        user1 = yunjiayiUserMapper.selectByPrimaryKey(userId);

        jsonObject.put("avatar", user1.getAvatar());
        jsonObject.put("realname", user1.getRealname());
        jsonObject.put("sex", user1.getSex()); // 性别，0为男，1为女
        jsonObject.put("phoneNumber", user1.getPhonenumber()); // 电话号码
        jsonObject.put("age", user1.getAge());// 年龄

        result.setCode(user1 != null ? 0 : 1);
        result.setMessage(user1 != null ? "获取成功" : "获取失败");
        result.setData(user1 != null ? jsonObject : null);
        return result;
    }

    //put,更新用户
    /*提交用户验证信息*/
    @PostMapping(path = "/verify")
    public Result updateUser(@RequestBody JSONObject object) {
        Result result = new Result();

        String token = gettoken();
        int userId = 0;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        try {
            YunjiayiUser user1 = yunjiayiUserMapper.selectByPrimaryKey(userId);

            user1.setStatusID(2);
            int tip = yunjiayiUserMapper.updateByPrimaryKey(user1);

            YunjiayiVerify verify=new YunjiayiVerify();

            verify.setUserID(userId);
            verify.setContent(object.getString("content"));
            verify.setFile(object.getJSONArray("files").toString());

            int inseVer = yunjiayiVerifyMapper.insert(verify);

            result.setCode(0);
            result.setMessage("提交成功");
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("提交失败");
        }

        return result;
    }

    /*修改密码*/
    @PutMapping(path = "/password")
    public Result password(@RequestBody Map<String, String> map) {
        Result result = new Result();

        String token = gettoken();
        int userId = 0;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception e) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        int tip;
        YunjiayiUser user1 = yunjiayiUserMapper.selectByPrimaryKey(userId);

        if (!user1.getPassword().equals(map.get("oldPassword"))) {
            result.setCode(1);
            result.setMessage("修改失败：原始密码错误");
        } else {
            user1.setPassword(map.get("newPassword"));
            tip = yunjiayiUserMapper.updateByPrimaryKey(user1);

            result.setCode(tip == 1 ? 0 : 1);
            result.setMessage(tip == 1 ? "修改成功" : "修改失败");
        }

        return result;
    }


    @CheckToken
    @GetMapping("/getMessage")
    public Result getMessage() {
        Result result = new Result();

        result.setData(gettoken());

        return result;
    }

    /*用户列表审核*/
    @GetMapping("/verify/list")
    public Result getverifylist() {
        Result result = new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }
        YunjiayiUser user=yunjiayiUserMapper.selectByPrimaryKey(myuserid);

        if (user.getIdentityId()!=6){
            result.setCode(1);
            result.setMessage("您还不是管理员无权查看");
            return result;
        }

        List<YunjiayiVerify> listVerify=yunjiayiVerifyMapper.selectAll();

        Author author=null;
        JSONObject object=null;
        List<Object> list=new ArrayList<>();

        try {
            for (YunjiayiVerify verify:listVerify){
                object=new JSONObject();

                object.put("id",verify.getVerifyID());

                author=new Author();
                author=yunjiayiUserMapper.selectPartInfo(verify.getUserID());

                object.put("author",author);
                object.put("createTime",verify.getCreatetime());
                object.put("abstract",verify.getContent());
                JSONArray array=JSONObject.parseArray(verify.getFile());
                if (array.size()==0){
                    object.put("firstPicture",null);
                }else {
                    object.put("firstPicture", array.get(0).toString());
                }
                list.add(object);
            }
            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(list);

        }catch (Exception e){
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return result;
    }

    /*获取验证材料详情信息*/
    @GetMapping("/verify")
    public Result getverify(@RequestParam("id") Integer id) {
        Result result = new Result();
        JSONObject object=new JSONObject();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        try {
            YunjiayiVerify verify=yunjiayiVerifyMapper.selectByPrimaryKey(id);

            Author author=yunjiayiUserMapper.selectPartInfo(verify.getUserID());

            object.put("author",author);
            object.put("createTime",verify.getCreatetime());
            object.put("content",verify.getContent());
            JSONArray array= JSONObject.parseArray(verify.getFile());
            object.put("files",array);

            result.setData(object);
            result.setMessage("查询成功");
            result.setCode(0);
            return result;
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("查询失败");
        }



        return result;
    }


    /*提交用户审核结果*/
    @PutMapping("/verify")
    public Result putverify(@RequestBody JSONObject object) {
        Result result = new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }


        YunjiayiVerify verify=yunjiayiVerifyMapper.selectByPrimaryKey(object.getInteger("id"));
        YunjiayiUser user=yunjiayiUserMapper.selectByPrimaryKey(verify.getUserID());

        try {
            if (object.getBoolean("isAgree")){
                user.setStatusID(user.getIdentityId());

                int updateUser=yunjiayiUserMapper.updateByPrimaryKey(user);

                int del=yunjiayiVerifyMapper.deleteByPrimaryKey(verify.getVerifyID());
            }else {
                user.setStatusID(1);
                int del=yunjiayiVerifyMapper.deleteByPrimaryKey(verify.getVerifyID());
            }

            result.setCode(0);
            result.setMessage("操作成功");
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("操作失败");
        }

        return result;
    }


    /*修改用户头像*/
    @RequestMapping(value = "/avatar", method = RequestMethod.PUT)
    public Result editAvatar(@RequestBody Map<String, String> map) {
        Result result = new Result();

        String token = gettoken();
        int userId=0;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (Exception j) {
            result.setCode(1);
            result.setMessage("您还没有登陆，请登陆");
            return result;
        }

        YunjiayiUser user = yunjiayiUserMapper.selectByPrimaryKey(userId);

        user.setAvatar(map.get("avatar"));

        int updateAvatar = yunjiayiUserMapper.updateByPrimaryKey(user);

        if (updateAvatar != 0) {
            result.setCode(0);
            result.setMessage("修改头像成功");
        } else {
            result.setCode(1);
            result.setMessage("修改头像失败");
        }

        return result;
    }

}